var db = require( '../db/db' );

const tableName = 'core.user_data';


exports.checkAuthority = async function (userId, uid) {

    let sql = `select user_id from ${tableName} where uid=$1`;
    let params = [uid];

    try {

        let result = await db.runSql(sql, params);

        if (result) {
            return result.rows[0].user_id == userId;
        }

        return false;

    } catch (e) {

        console.error( '检查用户权限失败' );
        return false;

    }
}

exports.updateMetadata = async function( uid, metadata ) {

    let sql = `update ${tableName} set metadata=$1 where uid=$2`;
    let params = [metadata, uid];

    try {
        let result = await db.runSql( sql, params );

        if (result) {
            return result.rows;
        }

        return null;

    } catch (e) {

        console.error( '更新元数据失败' );
        return null;

    }

}

exports.getByUid = async function(uid) {

    let sql = `select * from ${tableName} where uid=$1`;
    let params = [uid];

    try {

        let result = await db.runSql( sql, params );

        if (result) {
            return result.rows;
        }

        return null;

    } catch (e) {

        console.error(e);
        return null;

    }

}
